from app import db
from datetime import datetime

class AnswerKey(db.Model):
    __tablename__ = 'answer_keys'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    form_id = db.Column(db.BigInteger, db.ForeignKey('forms.id'), nullable=False)
    answer_content = db.Column(db.JSON, nullable=False, comment='答案内容(JSON格式)')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    created_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='创建人ID')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    updated_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='更新人ID')
    deleted_at = db.Column(db.DateTime, nullable=True, comment='删除时间(软删除)')
    deleted_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='删除人ID')
    
    # Define indexes
    __table_args__ = (
        db.Index('idx_form_id', form_id),
        db.Index('idx_deleted_at', deleted_at),
    )
    
    # Define relationships
    form = db.relationship('Form', foreign_keys=[form_id], backref=db.backref('answer_keys', lazy=True))
    creator = db.relationship('User', foreign_keys=[created_by], backref='created_answer_keys')
    updater = db.relationship('User', foreign_keys=[updated_by], backref='updated_answer_keys')
    deleter = db.relationship('User', foreign_keys=[deleted_by], backref='deleted_answer_keys')
    
    def __repr__(self):
        return f'<AnswerKey {self.id}>'